/**
 * Created by Mark on 2018/4/1.
 * 首页的逻辑
 */

require("./index.css");
require("page/common/nav/nav.js");
require("page/common/header/header.js");
var navSlider = require("util/slider/slider.js");/*引入轮播模板*/
var _productCategory = require("service/product-category-service.js");  //商品种类数据请求
var _headLine = require("service/headLine-service.js");  //头条
var templateSlider = require("./slider.string");
var _mm = require("util/mm.js");
var templateHtml = require("./index.string");
var $slider;
var page = {
    data : {
        parentCategoryId : _mm.getUrlParam("parentCategoryId") || "" //缓存一级商品种类的ID
    },
    init : function (){
        this.onLoad();
        this.bindEvent();
    },

    onLoad : function(){
        this.bannerInit();
    },
    onLoadSecondCategory : function (firstCategoryId) {
        _productCategory.getSecondlyCategoryList(firstCategoryId, function (res) {
            var html = _mm.renderHtml(templateHtml,res);
            $("#index").html(html);
        });
        
    }
    ,
    onLoadCategoryList : function () {
        _productCategory.getAllCategoryList( function (res) {
            var html = _mm.renderHtml(templateHtml,res);
            $("#index").html(html);
        }, function (err) {
            _mm.errorTips(err.msg);
        })
    },
    //1.页面初始化函数
    bannerInit : function(){//渲染轮播的HTML模板
        var _this = this;
        _headLine.getHeadLineList(function (res) {
            var bannerHtml = _mm.renderHtml(templateSlider,res.data);
            $(".banner-con").html(bannerHtml);
            $slider = $(".banner").unslider({  //初始化轮播图
                dots : true
            });
            if(_this.data.parentCategoryId){
                _this.onLoadSecondCategory(_this.data.parentCategoryId);//加指定一级商品种类下的所有商品种类
            }else{
                _this.onLoadCategoryList();//加载所有的商品种类列表
            }
        }, function (err) {
            _mm.errorTips(err.msg);
        })
    },
    //2.事件绑定函数
    bindEvent : function(){
        // 轮播图前一张和后一张操作的事件绑定
        $(document).on("click",".banner-con .banner-arrow", function () {
            var forward = $(this).hasClass('prev') ? 'prev' : 'next';
            $slider.data('unslider')[forward]();
        })
    }
};

$(function(){
    page.init();
});

